package com.quanyan.operative.service.impl;

import com.alibaba.fastjson.JSON;
import com.quanyan.api.APIResponse;
import com.quanyan.common.Plugin.PageObj;
import com.quanyan.common.http.HttpClientUtils;
import com.quanyan.messagepush.entity.Alert;
import com.quanyan.messagepush.entity.Payload;
import com.quanyan.messagepush.entity.PushMessage;
import com.quanyan.messagepush.entity.ReqPushMessage;
import com.quanyan.messagepush.enums.BoxName;
import com.quanyan.messagepush.enums.BoxType;
import com.quanyan.messagepush.enums.MsgType;
import com.quanyan.operative.mapper.*;
import com.quanyan.operative.model.db.*;
import com.quanyan.operative.model.req.ReqUserHitEgg;
import com.quanyan.operative.model.req.ReqUserReward;
import com.quanyan.operative.model.resp.RespActivityAndPrize;
import com.quanyan.operative.model.resp.RespPrize;
import com.quanyan.operative.model.resp.RespPrizeActivity;
import com.quanyan.operative.model.resp.RespUserHitEggInfo;
import com.quanyan.operative.service.DoubleEggFestivalService;
import com.quanyan.sms.service.SmsService;
import com.quanyan.user.response.RespUserInfoBase;
import com.quanyan.user.serviceFacade.UserServiceFacade;
import org.apache.commons.beanutils.BeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import sms.SmsApi;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 双蛋活动service实现
 * <p>
 * Created by huadongyang on 2016/12/6.
 */
@Service
public class DoubleEggFestivalServiceImpl implements DoubleEggFestivalService {
    private static final Logger logger = LoggerFactory.getLogger(DoubleEggFestivalServiceImpl.class);

    @Autowired
    private TbUserActivityRelationMapper tbUserActivityRelationMapper;

    @Autowired
    private DoubleEggFestivalMapper doubleEggFestivalMapper;

    @Autowired
    private TbOperatePrizeMapper tbOperatePrizeMapper;

    @Autowired
    private TbUserAwardListMapper tbUserAwardListMapper;

    @Autowired
    private TbOperateBlacklistMapper operateBlacklistMapper;

    @Value("${message.push.service.url}")
    private String messagePushServiceUrl;

    private static String LARK_LOGO = "lark_icon.png";

    private static final String SYSTEM_MESSAGE_URL = "http://quncao.b0.upaiyun.com/system/message/default/lark_f0bd80fb35f46bed00a15f1aebcb043b.png";


    @Autowired
    private SmsService smsService;

    @Autowired
    private UserServiceFacade userServiceFacade;

    private final Executor executor = Executors.newFixedThreadPool(2 * Runtime.getRuntime().availableProcessors());

    @Override
    public APIResponse getPrizeAndActivityList(Integer uid) {
        List<RespActivityAndPrize> activityPrizes = new ArrayList<>();
        try {
            List<RespPrizeActivity> prizeActivitys = doubleEggFestivalMapper.getPrizeActivityList();
            long nowTime = System.currentTimeMillis();
            if (prizeActivitys != null && prizeActivitys.size() > 0) {
                APIResponse<RespUserInfoBase> apiResponse = null;
                if (uid != null && uid > 0 ) {
                    apiResponse = userServiceFacade.queryUserInfo(uid);
                }
                for (RespPrizeActivity prizeActivity : prizeActivitys) {
                    RespActivityAndPrize respActivityAndPrize = new RespActivityAndPrize();

                    if (prizeActivity.getBeginTime().getTime() > nowTime) {
                        prizeActivity.setActivityStatus((byte) 1);  //活动未开始
                    } else if (nowTime >= prizeActivity.getBeginTime().getTime() && nowTime <= prizeActivity.getEndTime().getTime()) {
                        prizeActivity.setActivityStatus((byte) 2); //活动正在进行
                    } else if (nowTime > prizeActivity.getEndTime().getTime()) {
                        prizeActivity.setActivityStatus((byte) 3); //活动已结束
                    }
                    if (uid != null && uid > 0) {
                        //活动用户的蛋壳数量
                        TbUserActivityRelationExample activityRelationExample = new TbUserActivityRelationExample();
                        TbUserActivityRelationExample.Criteria criteria = activityRelationExample.createCriteria();
                        criteria.andActivityIdEqualTo(prizeActivity.getId());
                        criteria.andUidEqualTo(uid);
                        prizeActivity.setEggshellNum(tbUserActivityRelationMapper.countByExample(activityRelationExample));
                        if (apiResponse != null && apiResponse.getData() != null){
                            prizeActivity.setUserImageUrl(apiResponse.getData().getIcon());
                        }
                    }

                    respActivityAndPrize.setActivity(prizeActivity);
                    respActivityAndPrize.setPrizes(getPrizeList(prizeActivity.getId(), uid));

                    activityPrizes.add(respActivityAndPrize);
                }
            }
        } catch (Exception e) {
            logger.error("获取活动失败!:{}", e.getMessage());
            return APIResponse.returnFail("获取活动失败");
        }
        return APIResponse.returnSuccess(activityPrizes);
    }

    private List<RespPrize> getPrizeList(Integer activityId, Integer uid) {
        List<RespPrize> prizes = null;
        try {
            prizes = doubleEggFestivalMapper.getPrizeList(activityId);

            long nowTime = System.currentTimeMillis();
            if (prizes != null && prizes.size() > 0) {
                for (RespPrize respPrize : prizes) {
                    if (respPrize.getConvertedFrom().getTime() > nowTime) {
                        respPrize.setRewardStatus((byte) 1);  //兑奖未开始
                    } else if (nowTime >= respPrize.getConvertedFrom().getTime() && nowTime <= respPrize.getConvertedTo().getTime()) {
                        respPrize.setRewardStatus((byte) 2); //正在兑奖
                    } else if (nowTime > respPrize.getConvertedTo().getTime()) {
                        respPrize.setRewardStatus((byte) 3); //兑奖时间已过
                    }
                    if (uid != null && uid > 0) { //登录状态 用户是否兑奖
                        int userAwardCount = doubleEggFestivalMapper.userPrizeNum(uid,activityId,respPrize.getId());
                        if (userAwardCount <= 0) {
                            respPrize.setIsReward((byte) 1);   //未兑过
                        } else {
                            respPrize.setIsReward((byte) 2);   //已兑过
                        }
                    }

                }
            }
        } catch (Exception e) {
            logger.error("获取奖品列表失败!:{}", e.getMessage());
            return null;
        }
        return prizes;
    }

    @Override
    @Transactional
    public APIResponse helpFriendHitEgg(ReqUserHitEgg reqUserHitEgg) {
        TbUserActivityRelationExample example = new TbUserActivityRelationExample();
        TbUserActivityRelationExample.Criteria criteria = example.createCriteria();
        criteria.andUidEqualTo(reqUserHitEgg.getUid());
        criteria.andActivityIdEqualTo(reqUserHitEgg.getActivityId());
        criteria.andOpenIdEqualTo(reqUserHitEgg.getOpenId());
        List<TbUserActivityRelation> userActivityRelations = tbUserActivityRelationMapper.selectByExample(example);
        if (userActivityRelations != null && userActivityRelations.size() > 0) {
            return APIResponse.returnFail("已经帮好友砸过蛋了");
        }

        APIResponse<RespUserInfoBase> apiResponse = userServiceFacade.queryUserInfo(reqUserHitEgg.getUid());
        if (apiResponse != null && apiResponse.getData() != null) {
            reqUserHitEgg.setMobile(apiResponse.getData().getMobile());
        }

        TbUserActivityRelation record = new TbUserActivityRelation();
        record.setNum(1);
        try {
            BeanUtils.copyProperties(record, reqUserHitEgg);
            tbUserActivityRelationMapper.insertSelective(record);
        } catch (Exception e) {
            logger.error("帮好友砸蛋失败:{}", e.getMessage());
            return APIResponse.returnFail("帮好友砸蛋失败");
        }

        return APIResponse.returnSuccess();
    }

    @Override
    @Transactional
    public APIResponse getUserHitEggList(Integer uid, Integer activityId) {
        List<RespUserHitEggInfo> respUserHitEggInfos = null;

        try {
            respUserHitEggInfos = doubleEggFestivalMapper.getUserHitEggList(uid, activityId);
        } catch (Exception e) {
            logger.error("获取好友砸蛋列表失败！:{}", e.getMessage());
            return APIResponse.returnFail("获取好友砸蛋列表失败");
        }
        return APIResponse.returnSuccess(respUserHitEggInfos);
    }

    @Override
    @Transactional
    public APIResponse userReward(ReqUserReward reqUserReward) {
        Integer prizeId = reqUserReward.getPrizeId();
        Integer activityId = reqUserReward.getActivityId();
        final Integer uid = reqUserReward.getUid();
        final String mobile = reqUserReward.getMobile();

        TbOperatePrize operatePrize = null;
        try {
            operatePrize = tbOperatePrizeMapper.selectByPrimaryKey(prizeId);
            if (operatePrize == null) {
                return APIResponse.returnFail(100, "兑换奖品失败");
            }

            long nowTime = System.currentTimeMillis();
            if (nowTime < operatePrize.getConvertedFrom().getTime()) {
                return APIResponse.returnFail(101, "别着急,还没开始兑换奖品哦");
            }

            if (nowTime > operatePrize.getConvertedTo().getTime()) {
                return APIResponse.returnFail(102, "来晚了,兑奖时间已经过了");
            }

            if (operatePrize.getQuantity().intValue() <= 0) {
                return APIResponse.returnFail(103, "啊哦~很遗憾你来晚了一步," + operatePrize.getName() + "已经被抢光了,送你一个安慰吻,么么哒");
            }

            TbUserActivityRelationExample userActivityRelationExample = new TbUserActivityRelationExample();
            TbUserActivityRelationExample.Criteria activityRelationCriteria = userActivityRelationExample.createCriteria();
            activityRelationCriteria.andUidEqualTo(uid);
            activityRelationCriteria.andActivityIdEqualTo(activityId);
            int userEggshellCount = tbUserActivityRelationMapper.countByExample(userActivityRelationExample);
            if (userEggshellCount < operatePrize.getCondition()) {
                return APIResponse.returnFail(104, "蛋壳数量不够,不可兑换" + operatePrize.getName() + "奖品,继续努力~么么哒");
            }

            TbUserAwardListExample awardListExample = new TbUserAwardListExample();
            TbUserAwardListExample.Criteria awardListCriteria = awardListExample.createCriteria();
            awardListCriteria.andUidEqualTo(uid);
            awardListCriteria.andActivityIdEqualTo(activityId);
            int userAwardCount = tbUserAwardListMapper.countByExample(awardListExample);
            if (userAwardCount > 0) {
                return APIResponse.returnFail(105, "您已经领过礼品了，这个就让给其他人吧");
            }

            //验证黑名单
            TbOperateBlacklistExample blacklistExample = new TbOperateBlacklistExample();
            TbOperateBlacklistExample.Criteria blacklistCriteria = blacklistExample.createCriteria();
            blacklistCriteria.andMobileEqualTo(mobile.trim());
            int blackListCount = operateBlacklistMapper.countByExample(blacklistExample);

            if (blackListCount > 0) {
                return APIResponse.returnFail(103, "啊哦~很遗憾你来晚了一步," + operatePrize.getName() + "已经被抢光了,送你一个安慰吻,么么哒");
            }

            //消息文案
            final StringBuilder msg = new StringBuilder();
            final String args[] = new String[1];
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            if (nowTime <= sdf.parse("2016-12-29 23:59:59").getTime()) {
                msg.append("铛铛铛，恭喜您获得百灵鸟送出的圣诞大礼" + operatePrize.getName() + "一份，请静候客服小妹联系您领取礼品");
                args[0] = "圣诞大礼" + operatePrize.getName() + "一份";
            } else if (nowTime > sdf.parse("2016-12-29 23:59:59").getTime()) {
                msg.append("铛铛铛，恭喜您获得百灵鸟送出的元旦大礼" + operatePrize.getName() + "一份，请静候客服小妹联系您领取礼品噢！");
                args[0] = "元旦大礼" + operatePrize.getName() + "一份";
            }

            //更新库存
            int result = doubleEggFestivalMapper.updatePrizeQuantity(prizeId, operatePrize.getVersion());
            if (result > 0) { //成功
                TbUserAwardList tbUserAwardList = new TbUserAwardList();
                tbUserAwardList.setActivityId(activityId);
                tbUserAwardList.setUid(uid);
                tbUserAwardList.setMobile(mobile);
                tbUserAwardList.setPrizeId(prizeId);
                int userAwardResult = tbUserAwardListMapper.insertSelective(tbUserAwardList);
                if (userAwardResult > 0) {
                    executor.execute(new Runnable() {
                        @Override
                        public void run() {
                            pushMessage(uid, msg.toString());
                            smsService.sendMessageToPhone(mobile, SmsApi.MESSAGE_TEMPLATE_OPERATIVE_AWARD_NOTICE, args, true);
                        }
                    });
                }
            } else {
                //重试
                int resendResult = doubleEggFestivalMapper.updatePrizeQuantity(prizeId, operatePrize.getVersion());
                if (resendResult > 0) { //成功
                    TbUserAwardList tbUserAwardList = new TbUserAwardList();
                    tbUserAwardList.setActivityId(activityId);
                    tbUserAwardList.setUid(uid);
                    tbUserAwardList.setPrizeId(prizeId);
                    int userAwardResult = tbUserAwardListMapper.insertSelective(tbUserAwardList);
                    if (userAwardResult > 0) {
                        //推送消息和短信
                        executor.execute(new Runnable() {
                            @Override
                            public void run() {
                                pushMessage(uid, msg.toString());
                                smsService.sendMessageToPhone(mobile, SmsApi.MESSAGE_TEMPLATE_OPERATIVE_AWARD_NOTICE, args, true);
                            }
                        });

                    }
                } else {
                    return APIResponse.returnFail(106, "系统繁忙,请稍后重试");
                }

            }
        } catch (Exception e) {
            logger.error("领奖失败：{}", e.getMessage());
            return APIResponse.returnFail(100, "兑换奖品失败");
        }

        return APIResponse.returnSuccess("恭喜您获得由百灵鸟" + operatePrize.getName() + "节日大礼包一份");
    }

    /**
     * 推送消息
     *
     * @paraid
     */
    public void pushMessage(Integer uid, String msg) {
        //消息推送
        ReqPushMessage reqPushMessage = new ReqPushMessage();
        PushMessage pushMessage = new PushMessage();
        pushMessage.setTag(BoxName.CLUB.value() + System.currentTimeMillis());
        Alert alert = new Alert();
        alert.setBody("系统通知：" + msg);
        pushMessage.setAlert(alert);

        pushMessage.setTo(Arrays.asList(uid));
        pushMessage.setLogo(LARK_LOGO);
        pushMessage.setLogoUrl("");
        Payload payload = new Payload();
        payload.setBoxType(BoxType.SYSTEM_MSG.value());
        payload.setMsgType(MsgType.NOTIFY_MSG.value());
        payload.setTitle(msg);
        payload.setTimestamp(System.currentTimeMillis());
        payload.setImg(SYSTEM_MESSAGE_URL);
        pushMessage.setPayload(payload);
        reqPushMessage.setMsgList(Arrays.asList(pushMessage));

        String postJson = JSON.toJSONString(reqPushMessage);
        logger.info("推送消息：" + postJson);
        String result = null;

        try {
            result = HttpClientUtils.postJson(messagePushServiceUrl, postJson);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("推送消息失败", e.getMessage());
        }
        logger.info("推送返回：" + result);
    }

    @Override
    public APIResponse getUserEggshellNum(Integer uid, Integer activityId) {
        TbUserActivityRelationExample activityRelationExample = new TbUserActivityRelationExample();
        TbUserActivityRelationExample.Criteria criteria = activityRelationExample.createCriteria();
        criteria.andActivityIdEqualTo(activityId);
        criteria.andUidEqualTo(uid);
        int count = 0;
        try {
            count = tbUserActivityRelationMapper.countByExample(activityRelationExample);
        } catch (Exception e) {
            logger.error("获取用户蛋壳数量失败!:{}", e.getMessage());
            return APIResponse.returnFail("获取用户蛋壳数量失败！");
        }
        return APIResponse.returnSuccess(count);
    }
}
